package com.wangxinyuchuan.demo.singleton;

/**
 * 懒汉式
 * 虽然达到了按需初始化的目的，但是带来了线程不安全的问题
 * 加synchronized解决线程安全问题，但是效率会降低
 *
 * 下面这种依然有线程安全问题
 */
public class Demo5 {

    private static Demo5 INSTANCE;

    private Demo5() {

    }

    public static Demo5 getInstance() {
        if (null == INSTANCE) {
            synchronized (Demo5.class) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                INSTANCE = new Demo5();
            }
            return INSTANCE;
        }
        return INSTANCE;
    }


    public static void main(String[] args) {
//        Demo3 a = Demo3.getInstance();
//        Demo3 b = Demo3.getInstance();
//        System.out.println(a == b);

        // 模拟多线程获取单例对象
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(Demo5.getInstance());
            }).start();
        }
    }
}
